// pages/order/detail.js
import Router from '../../utils/router.js'
import util from '../../utils/util.js'
import base from '../../config/base.js'
import orderdetailsService from '../../services/orderinfo.js'
import confirmorderService from '../../services/confirmorder.js'
import orderlogisticsService from '../../services/orderlogistics.js'
import shareInfoJson from '../../utils/hbshare.js'
import storeservices from '../../services/store.js'
import redpacket from '../../utils/redpacket.js'
var orid = null,
  timer = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    kongge: ' ',
    info: {},
    // user_info: wx.getStorageSync('user_info'),
    activity: {},
    user_info: wx.getStorageSync('user_info'),
    infoflag: false,
    //按钮频繁拦截
    payflag: false,
    resource: {
      daifukuan: base.static + '/orders/details/daifukuan.png',
      daifahuo: base.static + '/orders/details/daifahuo.png',
      yifukuan: base.static + '/orders/details/yifukuan.png',
      yijiesuan: base.static + '/orders/details/yijiesuan.png',
      daishouhuo: base.static + '/orders/details/daishouhuo.png',
      shouhouzhong: base.static + '/orders/details/shouhouzhong.png',
      yiwancheng: base.static + '/orders/details/yiwancheng.png',
      yiquxiao: base.static + '/orders/details/yiquxiao.png',
      yituikuan: base.static + '/orders/details/yituikuan.png',
      dingwei: base.static + '/orders/details/zuobiaoshouhuodizhi.png',
      jiaoyiguanbi: base.static + '/orders/details/jiaoyiguanbi.png',
      dianpuimg: base.static + '/orders/dianpuimg.png',
      dianpuzuoj: base.static + '/orders/dianpuzuoj.png',
      wuliudetails: base.static + '/orders/details/wuliudetails.png',
      jiantdetails: base.static + '/orders/details/jiantdetails.png',
      order_suc_tk: base.static + '/redenvelopes/order_suc_fhbend.png',  
      order_suc_hb_fbtn: base.static + '/redenvelopes/order_suc_hb_fbtn.png',
      order_suc_close: base.static + '/redenvelopes/order_suc_close.png'
    },
    //分享 控制 
    share: {
      isShow: false,
      animate: false
    },
    update_status_str:'',
    wulist: [],
    wulistflag: 1,
    redDeflag: 0,
    cheap_status: 1,
    
  },
  goGonglue(){
    shareInfoJson.cardInfo.goGonglue();
  },
  closeredDe(){
    Router.go('myredinfo');
    this.setData({
      redDeflag: 0
    });
  },
  closeredDecatch(){},
  openshare: function (e) {
    if (this.data.cheap_status) {
      shareInfoJson.getbonusNum(this);
    } else {
      wx.showToast({
        title: '活动已结束！',
        icon: 'none',
        duration: 3000,
        complete:(res)=>{
          setTimeout(()=>{
            this.setData({
              redDeflag: 0
            });
          },1500)
        }
      })
    }
  },
  /**
   * 复制邀请码 
   */
  copyCode: function () {
    let c = this.data.info.run_num;
    wx.setClipboardData({
      data: c,
      success(res) {
        wx.showToast({
          title: '复制成功',
        });
      },
      fail(res) {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      },
    })
  },
  /**
   * 支付失败调用
   */
  payfail: function () {
    wx.showToast({
      title: '支付无效',
      icon: 'none'
    })
  },
  /**
   * 立即付款
   */
  gopayment: function (e) {
    let that = this,
      item = that.data.info,
      user_info = that.data.user_info,
      payflag = true,
      datas = {};
    if (that.data.payflag) { 
      return false;
    }
    that.setData({
      payflag
    });
    if (item.run_num == null || item.run_num == '') {
      that.payfail();
      return;
    }
    datas.run_num = item.run_num;
    if (user_info.openid == null || user_info.openid == '') {
      that.payfail();
      return;
    }
    datas.openid = user_info.openid;
    if (user_info.user_nickname == null || user_info.user_nickname == '') {
      that.payfail();
      return;
    }
    datas.bsln_name = user_info.user_nickname;
    that.toPay(datas);
  },
  // 支付
  toPay: function (data) {
    let that = this;    
    let opt = {
      run_num: data.run_num,
      orid: that.data.orid,
      total_money: 1,
      openid: data.openid,
      bsln_name: data.bsln_name,
    }
    confirmorderService.payOrder(opt, res => {
      if (res && res.code == 1) {
        let d = res.data;
        util.toPay(d, b => {
          if (b) {
            // 成功
            console.log(b);
            wx.showToast({
              title: '支付成功,加载中...',
              icon: 'none',
              complete: function () {
                that.cleartime();
                setTimeout(() => {
                  //支付成功，跳转详情页//singlePage
                  //获取 红包 
                  //let run_num = b.run_num;
                  //let orid = b.orid; 
                  Router.go('payhot', `orid=${that.data.orid}&run_num=${data.run_num}&store`);
                  //that.queryorderdetails(that.data.orid);
                  let activity = wx.getStorageSync('activity');
                  if (activity && activity.payorder_get_redpacket == 1) {
                    shareInfoJson.getSendRedEnvelope(that, () => {
                      that.setData({
                        redDeflag: 1
                      });
                    });
                  }
                }, 1500)
              },
            })
          } else {
            // 失败
            
          }
          let payflag = false;
          that.setData({
            payflag
          });
        })
      } else {
        let payflag = false;
        that.setData({
          payflag
        });
        return wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 5000
        });
      }
    }, res => {
      if (res && res.statusCode != 200) {
        let payflag = false;
        that.setData({
          payflag
        });
      }
    });

  },
  /**
   * 取消订单
   */
  cancelorder:function(){
    let that = this;
    wx.showModal({
      content: '确定取消订单吗？',
      success: function (res) {
        if (res.confirm){
          that.updatestatuswaitcancel();
        }
      }
    })
  },
  /**
   * 查看商品详情
   */
  goshopdetails: function (e) {
    var that = this,
      info = that.data.info,
      goods_id = info.goods_id,
      store_id = info.bslnid;
    if (goods_id == null || goods_id === '' || store_id === '' || store_id == null) {
      wx.showToast({
        title: '商品id无效',
        icon: 'none'
      })
      return;
    }
    if (info.bnorid == 0){
      Router.go('detail', `goods_id=${goods_id}&store_id=${store_id}`);      
    }
  },
  /**
   * 查看店铺详情
   */
  gostore:function(){
    var that = this,
      info = that.data.info,
      goods_id = info.goods_id,
      store_id = info.bslnid;
    if (goods_id == null || goods_id === '' || store_id === '' || store_id == null) {
      wx.showToast({
        title: '商品id无效',
        icon: 'none'
      })
      return;
    }
    Router.go('store', `store_id=${store_id}`, `reLaunch`);
  },
  /**
   * 物流详情
   */
  gologistics: function () {
    let that = this,
      info = that.data.info,
      courier_number = info.courier_number,
      express_company = info.express_company;
    if (express_company === '' || express_company == null) {
      express_company = '其他';
    }
    Router.go('logistics', `courier_number=${courier_number}&express_company=${express_company}&goods_img=${info.goods_img}`);
  },
  /**
   * 获取订单详情
   */
  queryorderdetails: function (status) {
    let that = this,
      param = {},
      infoflag = false;
    if (!orid) {
      wx.showToast({
        title: '暂无订单',
        icon: 'none',
        complete: function () {
          wx.navigateBack();
        }
      })
      return;
    }
    param.orid = orid;
    orderdetailsService.queryorderdetails(param, res => {
      // 成功
      if (res && res.code == 1) {
        let info = res.data,
          str_attr_val_name_obj = info.str_attr_val_name,
          str_attr_val_name = '';
        infoflag = true;
        for (let k in str_attr_val_name_obj) {
          str_attr_val_name += k + '：' + str_attr_val_name_obj[k] + '   ';
        }
        info.str_attr_val_name = str_attr_val_name;
        if (info.goods_img !== null && info.goods_img !== '' && info.goods_img.indexOf('http://') == -1 && info.goods_img.indexOf('https://') == -1){
          info.goods_img = 'http://' + info.goods_img + '?x-oss-process=image/resize,h_320';
        }
        if (info.goods_num === null || info.goods_num === '') {
          info.goods_num = 1;
        }
        if (info.buyer_name === null || info.buyer_name === '') {
          info.buyer_name = '';
        }
        if (info.tel !== undefined && info.tel === null || info.tel === '') {
          info.tel = '';
        }
        if (info.address !== undefined &&info.address === null || info.address === '') {
          info.address = '';
        }
        if (info.real_money !== undefined &&info.real_money !== null && info.real_money !== '') {
          info.real_money = util.toDecimal2(util.floatAccMul(info.real_money, 1));
        }
        if (info.total_money !== undefined &&info.total_money !== null && info.total_money !== '') {
          info.total_money = util.toDecimal2(util.toDecimal2(util.floatAccMul(info.total_money, 1)));
        }
        if (info.goods_num !== undefined &&info.goods_num !== null && info.goods_num !== '') {
          info.goods_num = util.floatAccMul(info.goods_num, 1);
        }
        if (info.postage !== undefined &&info.postage !== null && info.postage !== '') {
          info.postage = util.floatAccMul(info.postage, 1);
        }
        if (info.orig_price !== undefined &&info.orig_price !== null && info.orig_price !== '') {
          info.orig_price = util.toDecimal2(util.toDecimal2(util.floatAccMul(info.orig_price, 1)));
        }
        if (info.real_money !== undefined && info.real_money !== null && info.real_money !== '' && info.goods_num !== undefined && info.goods_num !== null && info.goods_num !== '') {
          info.goodszongnum = util.toDecimal2(util.floatAccMul(info.real_money, info.goods_num));
        } else {
          info.goodszongnum = info.real_money * info.goods_num;
        }
        if (info.score !== undefined && info.score !== null && info.score !== '') {
          info.score = util.toDecimal2(util.toDecimal2(util.floatAccMul(info.score, 1)));
        }
        if (info.cs_money !== undefined && info.cs_money !== null && info.cs_money !== '') {
          info.cs_money = util.toDecimal2(util.toDecimal2(util.floatAccMul(info.cs_money, 1)));
        }
        if (info.bybslt_money !== undefined && info.bybslt_money !== null && info.bybslt_money !== '') {
          info.bybslt_money = util.toDecimal2(util.toDecimal2(util.floatAccMul(info.bybslt_money, 1)));
        } 
        let discount_price = util.floatAccSub(info.orig_price ,info.total_money)
        info.discount_price = discount_price;
        // info.order_status = 3008;
        // info.surtime = 1000 * 5 * 1;
        info.surtime = 30 * 60 * 1000 - (that.parseDate(info.current_time) - that.parseDate(info.create_time));

        // if (info.order_status && info.surtime && info.order_status == 3009 & info.surtime < 0){
        //   info.surtime = 0;
        //   info.order_status = 3011;
        // }
        let update_status_str = that.data.update_status_str,
          order_status = info.order_status;
        if (order_status == 3011 && update_status_str == 'success_cancel'){
          wx.showToast({
            title: '订单已取消，退款将在1-3个工作日内退回至原支付账户，请耐心等待',
            icon: 'none',
            duration: 5000,
          })
        }
        update_status_str = '';
        that.setData({
          info, infoflag, orid, update_status_str
        });
        //待收货  已签收   待结算 已结算  建议关闭
        if (order_status == 3003 || order_status == 3004 || order_status == 3005 || order_status == 3006 || (order_status == 3013 && info.sale_time)) {
          that.queryorderlogistics();
        }
        if (info.order_status && info.surtime && info.order_status == 3009 && info.surtime > 0) {
          that.timeout();
        }

      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, (res) => {
      infoflag = true;
      wx.stopPullDownRefresh();
      that.setData({
        infoflag
      });
    });

  },
  /**
     * 获取物流
     */
  queryorderlogistics: function () {
    var that = this,
      info = that.data.info,
      courier_number = info.courier_number,
      express_company = info.express_company;
    let param = {
      courier_number: courier_number,
      express_company: express_company
    };
    if (courier_number && express_company){
      orderlogisticsService.queryorderlogistics(param, res => {
        if (res && res.code == 1) {
          let wulist = res.data;
          if (wulist && wulist.length > 0) {
            wulist = wulist[0];
          } else {
            wulist = [];
          }
          that.setData({
            wulist: [wulist]
          });
        }else{
          that.setData({
            wulist: []
          });
        }
      }, res => {
        that.setData({
          wulistflag: 2
        });
      });
    }else{
      that.setData({
        wulistflag: 2
      });
    }
  },
  /**
   * 清除定时任务
   */
  cleartime: function () {
    if (timer) {
      clearTimeout(timer);
    }
  },
  /**
   * 定时任务
   */
  timeout: function () {
    var that = this,
      info = that.data.info,
      surtime = info.surtime,
      seconds = Math.floor(surtime / 1000 / 60),
      minutes = (surtime - seconds * 60 * 1000) / 1000;
    that.setData({
      surtimetxt: `${seconds}分钟${minutes}秒后自动关闭`
    });
    timer = setTimeout(function () {
      if (info.surtime <= 0) {
        that.cleartime();
        that.updatestatuswaitcancel();
      } else {
        info.surtime = info.surtime - 1000;
        that.setData({
          info
        });
        that.timeout();
      }
    }, 1000);

  },
  /**
   * 待付款 变成 已取消
   */
  updatestatuswaitcancel: function () {
    let that = this,
      orid = that.data.orid,
      info = that.data.info,
      update_status = 3011,
      update_status_str = '',
      param = {};
    if (info.order_status == 3009) {
      update_status_str = 'wait_cancel';
    } else if (info.order_status == 3010) {
      update_status_str = 'success_cancel';
    } else if (info.order_status == 3003){
      update_status_str = 'have_send_have_get';      
    }
    that.setData({
      update_status_str
    });
    that.cleartime();
    if (!orid) {
      wx.showToast({
        title: '订单异常',
        icon: 'none'
      })
      return;
    }
    param.orid = orid;
    param.update_status = update_status_str;
    orderdetailsService.updatestatuswaitcancel(param, res => {
      if (res && res.code == 1) {
        //重新获取订单信息
        wx.showToast({
          title: '加载中...',
          icon: 'none',
          complete:function(){
            setTimeout(function () {
              that.queryorderdetails(orid);
            }, 1500);
          }
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  parseDate: function (time) {
    if (time) {
      time = time.replace(/-/g, "/");
      time = new Date(time).getTime();
      return time;
    }
  },
  //去售后类型页面
  goservicetype(){
    let orid = this.data.orid;
        Router.go('servicetype',`orid=${orid}`);
  },
  
  //点击确认收货
  goConfirmationReceipt(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    wx.showModal({
      content: '是否确认已收货？',
      cancelText: '取消',
      confirmText: '确认',
      confirmColor: '#FE3F3E',
      success(res) {
        if (res.confirm) {
          wx.showModal({
            content: '确认收货成功!\r\n快去发表评价吧！',
            cancelText: '取消',
            confirmText: '去评价',
            confirmColor: '#FE3F3E',
            success(res) {
              if(res.confirm){
                that.goevaluate()
              }
            }
          })
          that.updatestatuswaitcancel()
        }
      }
    })
  },
  //去评价页面
  goevaluate(e) {
    let that = this;
    let orid = that.data.options.orid;
    Router.go('evaluate', `orid=${orid}&page=detail`);
  }, 









  /**status
   * 1 待付款
   * 2 已付款
   * 3 待收货
   * 4 售后
   * 5 已签收
   * 6 已取消
   * 7 已退款
   */
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('detail onLoad')
    if (options.orid) {
      orid = options.orid;
    }
    this.setData({
      options,
      user_info:wx.getStorageSync('user_info'),
      activity: wx.getStorageSync('activity')
    })
    wx.hideShareMenu();
    redpacket.getcheap_goods(this);
    if (options.scene && options.scene == 'singlePage') {
      shareInfoJson.getSendRedEnvelope(this, () => {
        this.setData({
          redDeflag: 1
        });
      });
    }
    this.queryorderdetails(orid);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    that.cleartime();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    that.cleartime();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.cleartime();
    that.queryorderdetails(orid);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let shareObj = {
      title: shareInfoJson.cardInfo.titlefn(),
      path: shareInfoJson.cardInfo.pathFn(this) + `&hb_sharePath=orderDetail`,
      imageUrl: shareInfoJson.cardInfo.imageUrl,
      success: function (res) {
        console.log(res, 'success');
      },
      fail: function (res) {
        console.log(res, 'fail');
      },
      complete: function () {
        console.log('complete');
      }
    }
    // if(options.from == 'button'){
    //   shareObj.path = '/pages/my/joinshopman?shareType=1';
    // }
    return shareObj;
  }
})